﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using OSGeo.MapGuide;
using System.Configuration;


namespace NegevGas
{
    /// <summary>
    /// Summary description for GService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [ScriptService] 
    public class GService : System.Web.Services.WebService
    {
   
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        [WebMethod]

        public string GetData(int id)
        {






















            return id.ToString() + "i am jason ";
        }
    



        [WebMethod]
        public string AddNaaz(double X, double Y, string MapSession, string mapName)
        {
            try
            {
                string dataSource = "Session:" + MapSession + "//RedlineSymbol.FeatureSource";
                string layerDef = "Session:" + MapSession + "//RedlineSymbol.LayerDefinition";
                //  MgSiteConnection site = MGMapObject.GetMgSite(MapSession);


                MgUserInformation userInfo = new MgUserInformation(MapSession);
                MgSiteConnection siteConnection = new MgSiteConnection();
                siteConnection.Open(userInfo);

                // Create a ReserviceService object and use it to open the Map
                // object from the sessions repository. Use the Map object to
                // determine if the "AddressMarker" layer is visible.

                MgResourceService resourceService = siteConnection.CreateService(MgServiceType.ResourceService) as MgResourceService;
                MgMap map = new MgMap();
                map.Open(resourceService, mapName);
              //  MgLayer locationLayer = GetLayerByName(map, "LocationMarker");



                if (siteConnection == null)
                {
                    return "יש לרענן את האתר , לחיצה על כפתור הבית בפינה השמאלית עליונה";
                }
                MgFeatureService featureSrvc = siteConnection.CreateService(2) as MgFeatureService;
                MgResourceService resourceSrvc = siteConnection.CreateService(0) as MgResourceService;
                MgResourceIdentifier dataSourceId = new MgResourceIdentifier(dataSource);
                MgResourceIdentifier layerDefId = new MgResourceIdentifier(layerDef);
                //MgMap map = MGMapObject.GetMgMap(resourceSrvc, mapName);
                MgGeometryFactory geomFactory = new MgGeometryFactory();
                MgPoint geom = geomFactory.CreatePoint(geomFactory.CreateCoordinateXY(X, Y));
                if (DataSourceExists(resourceSrvc, dataSourceId))
                {
                    resourceSrvc.DeleteResource(dataSourceId);
                }
                MgClassDefinition classDef = CreateFeatureClass("RedlineSymbol", "RedlineSymbol");
                AddFeatureClassProperty(classDef, "KEY", 7, true);
                SetGeometryProp(classDef);
                MgFeatureSchema schema = CreateSchema(classDef, "RedlineSymbolShema", "RedlineSymbolShema");
                MgCreateSdfParams parameters = new MgCreateSdfParams("ArbitraryXY", GetMapSrs(map), schema);
                featureSrvc.CreateFeatureSource(dataSourceId, parameters);
                MgLayerCollection layers = map.GetLayers();
                MgLayer layer = FindLayer(layers, layerDef);
                LayerDefinitionFactory LayerDeffactory = new LayerDefinitionFactory();
                if ((layer == null) && LayerDeffactory.CreateLayerDef("SymbolLayerDef_Cell", dataSource, "RedlineSymbol", ""))
                {
                    resourceSrvc.SetResource(layerDefId, LayerDeffactory.layerDefContent, null);
                    layer = new MgLayer(layerDefId, resourceSrvc);
                    layer.SetDisplayInLegend(false);
                    layer.SetSelectable(false);
                    layer.SetVisible(true);
                    layer.SetLegendLabel("ZoomSymbol");
                    layers.Insert(0, layer);
                }
                MgPropertyCollection featureProps = new MgPropertyCollection();
                AddPointFeature("RedlineSymbol", featureProps, geom, featureSrvc, dataSourceId);
                if (layer != null)
                {
                    layer.ForceRefresh();
                }
                map.Save(resourceSrvc);
                siteConnection = null;
                map = null;
                dataSourceId = null;
                layerDefId = null;
                featureSrvc = null;
                resourceSrvc = null;
                geomFactory = null;
                geom = null;
                classDef = null;
                schema = null;
                featureProps = null;
                parameters = null;
                layers = null;
                layer = null;
                LayerDeffactory = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                return "Ok";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public string HelloWorld()
        {
            return "Hello World";
        }


        public static MgClassDefinition CreateFeatureClass(string name, string desc)
        {
            MgClassDefinition classDef = new MgClassDefinition();
            classDef.SetName(name);
            classDef.SetDescription(desc);
            classDef.SetDefaultGeometryPropertyName("GEOM");
            return classDef;
        }

        public static void AddFeatureClassProperty(MgClassDefinition classDef, string name, int itype, bool isKey)
        {
            MgDataPropertyDefinition prop = new MgDataPropertyDefinition(name);
            prop.SetDataType(itype);
            if (isKey)
            {
                prop.SetAutoGeneration(true);
                classDef.GetIdentityProperties().Add(prop);
                prop.SetReadOnly(true);
            }
            else
            {
                prop.Nullable = true;
            }
            classDef.GetProperties().Add(prop);
        }
        public static void SetGeometryProp(MgClassDefinition classDef)
        {
            MgGeometricPropertyDefinition geomProp = new MgGeometricPropertyDefinition("GEOM");
            geomProp.SetGeometryTypes(4);
            classDef.GetProperties().Add(geomProp);
        }
        public static MgFeatureSchema CreateSchema(MgClassDefinition classDef, string name, string desc)
        {
            MgFeatureSchema schema = new MgFeatureSchema(name, desc);
            schema.GetClasses().Add(classDef);
            return schema;
        }


        public static bool DataSourceExists(MgResourceService resourceSrvc, MgResourceIdentifier dataSourceId)
        {
            try
            {
                string MGServerVersion = ConfigurationManager.AppSettings["MGServerVersion"];
                if (MGServerVersion == "2009")
                {
                    MgByteReader cnt = resourceSrvc.GetResourceContent(dataSourceId);
                    cnt = null;
                    return true;
                }
                return resourceSrvc.ResourceExists(dataSourceId);
            }
            catch (MgResourceNotFoundException)
            {
                return false;
            }
        }
        public static MgLayer FindLayer(MgLayerCollection layers, string layerDef)
        {
            for (int i = 0; i < layers.GetCount(); i++)
            {
                MgLayer layer1 = (MgLayer)layers.GetItem(i);
                if (layer1.GetLayerDefinition().ToString() == layerDef)
                {
                    return layer1;
                }
            }
            return null;
        }
        public static void AddPointFeature(string FeatureName, MgPropertyCollection featureProps, MgPoint geom, MgFeatureService featureSrvc, MgResourceIdentifier dataSourceId)
        {
            MgByteReader geomReader = new MgAgfReaderWriter().Write(geom);
            MgGeometryProperty geometryProp = new MgGeometryProperty("GEOM", geomReader);
            featureProps.Add(geometryProp);
            MgInsertFeatures cmd = new MgInsertFeatures(FeatureName, featureProps);
            MgFeatureCommandCollection commands = new MgFeatureCommandCollection();
            commands.Add(cmd);
            ReleaseReader(featureSrvc.UpdateFeatures(dataSourceId, commands, false));
        }

        public static void ReleaseReader(MgPropertyCollection res)
        {
            if (res != null)
            {
                MgProperty prop = res.GetItem(0);
                if (prop != null)
                {
                    if (prop is MgStringProperty)
                    {
                        throw new Exception(((MgStringProperty)prop).GetValue());
                    }
                    MgFeatureReader reader = ((MgFeatureProperty)prop).GetValue();
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
            }
        }
        public static string GetMapSrs(MgMap map)
        {
            string srs = map.GetMapSRS();
            if (srs != "")
            {
                return srs;
            }
            return "LOCALCS[\"Non-Earth (Meter)\",LOCAL_DATUM[\"Local Datum\",0],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]]";
        }
    }
}
